﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using commfuncs.Search;
using System.Data;
using micsun.Logic;

namespace tmsWeb
{
    public partial class SearchHis : micsun.Web.SecurityPage
    {
        SearchBL sBl = new SearchBL();
        string BaseDir = micsunConfiguration.GetParameter("DataBaseFilePath").ToString();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                SetDropDownListOnLoad();
                loadDataYearsFromFiles();
            }
        }
        protected override void OnUnload(EventArgs e)
        {
            //sBl.DropLastTempHeapTable();
            base.OnUnload(e);
            
        }
        #region Search Prepare...
        void SetDropDownListOnLoad()
        {
            DataTable dt =  sBl.GetSitTableListForDrop(1);

            ddlStation.DataSource = dt;
            ddlStation.DataValueField = "TreeID";
            ddlStation.DataTextField = "SiteName";
            ddlStation.DataBind();

            if (dt.Rows.Count > 0)
            {
                int pId = Convert.ToInt32(dt.Rows[0]["TreeID"]);
                DataTable dt1 = setPlace(pId);

                if (dt1.Rows.Count > 0)
                {
                    string siteId = dt1.Rows[0]["SiteID"].ToString();
                    setTemperature(siteId);
                }
                else
                {
                    btnGo.Enabled = false;
                }
            }
            else
            {
                btnGo.Enabled = false;
            }

        }

        DataTable setPlace( int pId)
        {
            DataTable dt1 = sBl.GetSitTableListForDrop(2, pId);

            ddlPlace.DataSource = dt1;
            ddlPlace.DataValueField = "SiteID";
            ddlPlace.DataTextField = "SiteName";
            ddlPlace.DataBind();

            return dt1;
        }

        void setTemperature(string siteID)
        {
            DataTable dt2 = sBl.GetSitTableListForDrop(siteID);

            ddlTemperature.DataSource = dt2;
            ddlTemperature.DataValueField = "SsrKey";
            ddlTemperature.DataTextField = "SsrName";
            ddlTemperature.DataBind();

            if (dt2.Rows.Count == 0)
            {
                btnGo.Enabled = false;
            }
            else
            {
                string ssrKey = dt2.Rows[0]["SsrKey"].ToString();
                loadTemperatureInfo(ssrKey);

            }
        }

        void loadTemperatureInfo(string ssrkey)
        {
            DataTable dt = sBl.GetSensorInfo(ssrkey);
            lblId.Text = dt.Rows[0]["SsrKey"].ToString();
            lblName.Text = dt.Rows[0]["SsrName"].ToString();
            if (dt.Rows[0]["Max_Limit"] != DBNull.Value && dt.Rows[0]["Max_Limit"].ToString() != string.Empty)
            {
                lblMax.Text = dt.Rows[0]["Max_Limit"].ToString();
            }
            if (dt.Rows[0]["Min_Limit"] != DBNull.Value && dt.Rows[0]["Min_Limit"].ToString() != string.Empty)
            {
                lblMin.Text = dt.Rows[0]["Min_Limit"].ToString();
            }
        }

        void loadDataYearsFromFiles()
        {
            ddlDateSelect.Items.Clear();
            string[] dir = Directory.GetDirectories(BaseDir);

            
            for (int i = 0; i < dir.Length; i++)
            {
                string disText = dir[i].Replace(BaseDir, "").Replace("_", "年").TrimStart('\\');
                ddlDateSelect.Items.Add(new ListItem(disText + "月", BaseDir+"\\\\"+disText.Replace("年","_")));
                
            }
            
        }
       
        protected void ddlStation_SelectedIndexChanged(object sender, EventArgs e)
        {
           
                int pId = Convert.ToInt32(ddlStation.SelectedValue);
                DataTable dt1 = setPlace(pId);

                if (dt1.Rows.Count > 0)
                {
                    string siteId = dt1.Rows[0]["SiteID"].ToString();
                    setTemperature(siteId);
                }
            
        }

        protected void ddlPlace_SelectedIndexChanged(object sender, EventArgs e)
        {
            string siteId = ddlPlace.SelectedValue.ToString();
            setTemperature(siteId);
        }

        protected void ddlTemperature_SelectedIndexChanged(object sender, EventArgs e)
        {
            string ssrKey = ddlTemperature.SelectedValue.ToString();
            loadTemperatureInfo(ssrKey);
        }
        #endregion

        #region State events...
        protected void ddlDateType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlDateType.SelectedIndex == 0)
            {
                PanelData.Visible = false;
            }
            else
            {
                PanelData.Visible = true;
            }
        }

        protected void btnGo_Click(object sender, EventArgs e)
        {
            if (!CheckInput())
            {
                return;
            }
            string ssrKey = ddlStation.SelectedValue;
            string condTemp = string.Empty;
            string condalarm = string.Empty;
            string condList = "SsrKey='"+ddlTemperature.SelectedValue+"'";
            if (CheckBoxTemp.Checked)
            {
                switch (ddlDateType0.SelectedIndex)
                {
                    case 0:
                        condTemp = " ResValue >=" + TextBox1.Text;
                        break;
                    case 1:
                        condTemp = " ResValue <=" + TextBox1.Text;
                        break;
                    default:
                        condTemp = " ResValue >=" + TextBox1.Text + " and ResValue <=" + TextBox2.Text;
                        break;
                }
            }

            if (CheckBoxAlarm.Checked)
            {
                if (RadioButton1.Checked)
                {
                    condalarm = " IsAlarm = 1";
                }
                else
                {
                    condalarm = " IsAlarm = 0";
                }
            }
            if (condTemp != string.Empty)
            {
                condList += " and " + condTemp;
                if (condalarm != string.Empty)
                {
                    condList += " and " + condalarm;
                }
            }
            else if(condalarm !=string.Empty)
            {
                condList += " and " + condalarm;
            }

            GetResults(condList);
        }

        private void GetResults(string condList)
        {
            ResultDG.SelectList = "*";

            if (ddlDateType.SelectedIndex == 0)//从当前数据库表中直接取出数据
            {
                ResultDG.TableList = "t_supervise";
            }
            else
            {
                //建立数据库临时表,根据用户不同,临时表将使用为每个用户定制的临时表,临时表名为Temp_ + user.UniqueID
                string tempTableName = "temp_" + this.User.GetHashCode().ToString();
                string selectedDir = ddlDateSelect.SelectedValue;

                //取得表数据
                string[] fileNameStr = Directory.GetFiles(selectedDir);
                if (this.User.LastTempTable == tempTableName)
                {
                    sBl.DeleteTempTableData(tempTableName);//清除临时表中的数据备用
                }
                else
                {

                    //建立内存临时表
                    sBl.CreateTempHeapTable(tempTableName);
                    this.User.LastTempTable = sBl.LastTempHeapTable;
                }
                //表内插入数据
                sBl.InsertFilesDataToTempHeapTable(fileNameStr, tempTableName);
                ResultDG.TableList = tempTableName;
                ResultDG.Conn = SearchBL.Conn;
                //
            }
            ResultDG.KeyIDName = "KeyId";
            ResultDG.WhereList = condList;
            ResultDG.KeyIDPosition = new int[] { 1 };
            ResultDG.BindData(BindDataType.搜索位置);
        }
        private bool CheckInput()
        {
            double result = 0; double result1 = 0;
            if (CheckBoxTemp.Checked)
            {
                if (TextBox1.Text.Trim() == string.Empty)
                {
                    ScriptManager.RegisterStartupScript(UpdatePanel1, typeof(UpdatePanel), "show", "alert('温度条件不能为空!');", true);
                    return false;
                }
                else if (!double.TryParse(TextBox1.Text, out result))
                {
                    ScriptManager.RegisterStartupScript(UpdatePanel1, typeof(UpdatePanel), "show", "alert('温度条件应为数字!');", true);
                    return false;
                }
                if (ddlDateType0.SelectedIndex == 2 && TextBox2.Text.Trim() == string.Empty)
                {
                    ScriptManager.RegisterStartupScript(UpdatePanel1, typeof(UpdatePanel), "show", "alert('上限温度条件不能为空!');", true);
                    return false;
                }
                else if (ddlDateType0.SelectedIndex == 2 && !double.TryParse(TextBox2.Text, out result1))
                {
                    ScriptManager.RegisterStartupScript(UpdatePanel1, typeof(UpdatePanel), "show", "alert('上限温度条件应为数字!');", true);
                    return false;
                }

                if (ddlDateType0.SelectedIndex == 2 && result >= result1)
                {
                    ScriptManager.RegisterStartupScript(UpdatePanel1, typeof(UpdatePanel), "show", "alert('上限温度条件应大于下限温度条件!');", true);
                    return false;
                }
            }
            if (ddlDateType.SelectedIndex == 1 && ddlDateSelect.Items.Count == 0)
            {
                ScriptManager.RegisterStartupScript(UpdatePanel1, typeof(UpdatePanel), "show", "alert('没有历史数据可用来查询!');", true);
                return false;
            }
            return true;

        }
        protected void CheckBoxTemp_CheckedChanged(object sender, EventArgs e)
        {
            
            ddlDateType0.Enabled = PanelTMax.Enabled = CheckBoxTemp.Checked;
        }

        protected void CheckBoxAlarm_CheckedChanged(object sender, EventArgs e)
        {
            Panel1.Enabled = CheckBoxAlarm.Checked;
        }

        protected void ddlDateType0_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlDateType0.SelectedIndex == 2)
            {
                PanelTMin.Visible = true;
            }
            else
            {
                PanelTMin.Visible = false;
            }
        }
        #endregion
    }
}
